package servlets;

import game.GameData;
import game.GameLogic;
import game.resources.Chat;
import game.resources.Profile;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ecs.xml.XML;

import server.DBLogic;
import server.resources.XMLFactory;


public class GetGame extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	       DBLogic dbl = new DBLogic();
	        dbl.InitDBConnection();
	        
	        response.setContentType("text/xml");
	        response.setHeader("Cache-Control", "no-cache");
	        
	        String requestType = request.getParameter("type");
	        
	        XML resp = new XML("status");
	        
	        Cookie[] cookies = request.getCookies();
	        String rawRoomID = null;
	        String playerIndex = null;
	        
	        for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("roomID")) {
	                rawRoomID = cookie.getValue();
	            }
	            if (cookie.getName().equals("playerIndex")) {
	                playerIndex = cookie.getValue();
	            }
	        }
	        
	        if (rawRoomID == null) {
	            resp.addElement("no-game");
	        } else {
	            try {
	                int roomID = Integer.parseInt(rawRoomID);
	                if (requestType.equals("getGameLog")) {
	                    String log = dbl.queryGameLog(roomID);
	                    if (log != null) {
	                        resp.addElement(log);
	                    } else {
	                        resp.addElement("bad-roomID");
	                    }
	                } else if (requestType.equals("getPrivateGameLog")) {
                        String log = dbl.queryPrivateGameLog(roomID);
                        if (log != null) {
                            resp.addElement(log);
                        } else {
                            resp.addElement("bad-roomID");
                        }
                    } else if (requestType.equals("getGameData")) {
	                    String gameData = dbl.queryGameData(roomID);
	                    if (gameData != null) {
                            resp.addElement(gameData);
                        } else {
                            resp.addElement("bad-roomID");
                        }  
                    } else if (requestType.equals("getActionCounter")) {
	                    int actionCounter = dbl.queryActionCounter(roomID);
	                    if (actionCounter != -1) {
                            resp.addElement(Integer.toString(actionCounter));
                        } else {
                            resp.addElement("bad-roomID");
                        }  
	                } else if (requestType.equals("getChatMessages")) {
	                    Chat chat = new Chat(roomID);
	                    String message = chat.recieveMsg(Integer.parseInt(playerIndex));
	                    if (message == null) {
	                        resp.addElement("");                        
	                    } else {
	                        resp.addElement(message);
	                    }
                    } else {
	                    resp.addElement("bad-command");
	                }
	            } catch (SQLException e) {
	                resp.addElement("db-problem");
	            } catch (NumberFormatException e1) {
	                resp.addElement("bad-roomID");
	            }
	        }
	    
	        response.getWriter().write(resp.toString());
	        dbl.ShutDBConnection();
	}


	@SuppressWarnings("unchecked")
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBLogic dbl = new DBLogic();
        dbl.InitDBConnection();
        
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
        String requestType = request.getParameter("type");
        
        Map<String, String[]> requestMap = (Map<String, String[]>)request.getParameterMap();
        Map<String, String> params = new HashMap<String, String>();
        for (Entry<String, String[]> entry : requestMap.entrySet()) {
            if (!entry.getKey().equals("type"))
                params.put(entry.getKey(), entry.getValue()[0]);
        }
        
        XML resp = new XML("status");
        
        Cookie[] cookies = request.getCookies();
        String rawRoomID = null;
        String playerIndex = null;
        String userID = null;
              
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("roomID")) {
                rawRoomID = cookie.getValue();
            } 
            if (cookie.getName().equals("playerIndex")) {
                playerIndex = cookie.getValue();
            }
            if (cookie.getName().equals("userID")) {
                userID = cookie.getValue();
            }
            
        }
        
        if (rawRoomID == null) {
            resp.addElement("no-game");
        } else {
            try {
                int roomID = Integer.parseInt(rawRoomID);
                if (requestType.equals("postGameData")) {
                    String rawGameData = dbl.queryGameData(roomID);
                    if (rawGameData != null) {
                        GameData gameData = XMLFactory.getGameDataFromXML(rawGameData);
                        GameLogic game = new GameLogic();
                        game.execute(gameData, params);
                        dbl.updateGameData(roomID, XMLFactory.getGameDataXML(game.getGameData()),game.getGameData().getActionCounter());
                        resp.addElement("updated");
                    } else {
                        resp.addElement("bad-roomID");
                    }  
                } else if (requestType.equals("postChatMessage")) {
                    Profile player = dbl.queryProfile(Long.parseLong(userID));
                    
                    String message = params.get("chatMessage");
                    Chat chat = new Chat(roomID);
                    boolean sent = chat.sendMsg(Integer.parseInt(playerIndex), player.getFullName(), message);
                    if (!sent) {
                        resp.addElement("not-sent ");
                    } else {
                        resp.addElement("sent-message");
                    }
                } else {
                    resp.addElement("bad-command");
                }
            } catch (SQLException e) {
                resp.addElement("db-problem");
            } catch (NumberFormatException e1) {
                resp.addElement("bad-roomID");
            }
        }
        
        response.getWriter().write(resp.toString());
        dbl.ShutDBConnection();
	}

}
